package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import cn.com.elite.Util;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.ParseException
import java.text.SimpleDateFormat;
import java.time.Instant

import org.apache.commons.codec.binary.Base64
import org.apache.commons.codec.digest.DigestUtils
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import cn.com.kh.hst.ThreeDesUtil
import cn.com.kh.KHUtil;
import cn.com.kh.getProperty;


/**
 *
 * @Title: aipHSTRecycle_operation
 * @Description:华盛证券 回收
 * @author: xrm
 * @date 2022-12-20 15:52:00
 *
 */

public class aipHSTRecycle_operation implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTRecycle_operation.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String totalData = "";
        String dataSourceID = "dataSource";


        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;
            log.debug("dayin");
            JSONObject inObject = new JSONObject(inData);
            log.debug("原始inObject inObject:" + inObject);

            def recovery_guid = inObject.getString("recovery_guid");//回收规则id
            log.debug("回收规则id:" + recovery_guid);

            //根据回收任务id查询出回收任务条件
            List hst_recycle_ruleslist = eliteBean.chaxun_sql("select recovery_name,advisory_groupid,channel_id,account_openingid,deposit_statusid,retain_type,retain_day,recovery_frequency,expiration_prompt,allocation_day from hst_recycle_rules where recovery_guid='" + recovery_guid + "'", "dataSource");
            String recovery_name = hst_recycle_ruleslist.get(0).get("recovery_name");//规则名称
            String advisory_groupid = hst_recycle_ruleslist.get(0).get("advisory_groupid");//选择服顾组
            advisory_groupid = advisory_groupid.replace(",", "','");
            String channel_id = hst_recycle_ruleslist.get(0).get("channel_id");//选择渠道id
            channel_id = channel_id.replace(",", "','");
            String account_openingid = hst_recycle_ruleslist.get(0).get("account_openingid");//开户状态
            account_openingid = account_openingid.replace(",", "','");
            String deposit_statusid = hst_recycle_ruleslist.get(0).get("deposit_statusid");//入金状态
            deposit_statusid = deposit_statusid.replace(",", "','");
            String retain_type = hst_recycle_ruleslist.get(0).get("retain_type");//分配保留效期类型
            String retain_day = hst_recycle_ruleslist.get(0).get("retain_day");//分配保留效期
            String recovery_frequency = hst_recycle_ruleslist.get(0).get("recovery_frequency");//回收频次
            String expiration_prompt = hst_recycle_ruleslist.get(0).get("expiration_prompt");//是否到期提示
            String allocation_day = hst_recycle_ruleslist.get(0).get("allocation_day");//分配时间大于

            def allocation_day2 = Integer.parseInt(allocation_day)

            def expiration_prompttime = '';//到期提示时间

            log.debug("advisory_groupid:" + advisory_groupid + "|channel_id:" + channel_id + "|account_openingid:" + account_openingid + "|retain_type:" + retain_type + "|retain_day:" + retain_day+"|分配时间大于:"+allocation_day2);

            //根据分配保留效期类型及分配保留效期计算分配保留效期具体日期
            def retain_time = '';//分配保留效期具体日期
            log.debug("1");
            def retain_day2 = '';//计算后的分配保留效期
            log.debug("2");
            List retain_timelist = new ArrayList<>();
            log.debug("retain_type:" + retain_type);

            if (retain_type == "1") {//分配保留效期类型为每日
                retain_timelist = eliteBean.chaxun_sql("select date_add(now(), interval '" + retain_day + "' day) as retain_time", "dataSource");//计算分配保留效期具体日期
                retain_time = retain_timelist.get(0).get("retain_time");
            }

            if (retain_type == "2") {//分配保留效期类型为每周
                retain_day2 = Integer.parseInt(retain_day) * 7;
                log.debug("retain_day2:" + retain_day2);
                retain_timelist = eliteBean.chaxun_sql("select date_add(now(), interval '" + retain_day2 + "' day) as retain_time", "dataSource");//计算分配保留效期具体日期
                retain_time = retain_timelist.get(0).get("retain_time");
            }

            if (retain_type == "3") {//分配保留效期类型为每月
                List daylist = eliteBean.chaxun_sql("select day(last_day(NOW())) as day", "dataSource");
                Integer day = daylist.get(0).get("day");//获取本月多少天
                retain_day2 = Integer.parseInt(retain_day) * day;
                retain_timelist = eliteBean.chaxun_sql("select date_add(now(), interval '" + retain_day2 + "' day) as retain_time", "dataSource");//计算分配保留效期具体日期
                retain_time = retain_timelist.get(0).get("retain_time");
            }
            log.debug("retain_time:" + retain_time);

            log.debug("expiration_prompt:" + expiration_prompt);
            if (expiration_prompt == "0") {
                List expiration_promptlist = eliteBean.chaxun_sql("select date_add('" + retain_time + "', interval -3 day) as expiration_prompt", "dataSource");//计算到期提示时间
                expiration_prompttime = expiration_promptlist.get(0).get("expiration_prompt");
                log.debug("expiration_prompttime:" + expiration_prompttime);
            }

            //创建一个批次号
            long time = new Date().getTime();
            System.out.println("" + time);
            Date dates = new Date(time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            String times = sdf.format(dates);

            String advisory_batchid = "回收批次" + times; //批次号

            if (KHUtil.isNull(account_openingid)) {
                account_openingid = ''
            } else {
                account_openingid = "and c.registerstatus in ('" + account_openingid + "')"
            }

            if (KHUtil.isNull(channel_id)) {
                channel_id = ''
            } else {
                channel_id = "and c.sq_9 in ('" + channel_id + "')"
            }

            if (KHUtil.isNull(deposit_statusid)) {
                deposit_statusid = ''
            } else {
                deposit_statusid = "and c.depositstatus in ('" + deposit_statusid + "')"
            }


            //根据回收任务条件查询出对应的数据
            List objectivelist = eliteBean.chaxun_sql("SELECT o.OBJECTIVE_GUID as OBJECTIVE_GUID,o.CUSTOMER_GUID as CUSTOMER_GUID,e.CREATEDDATE as CREATEDDATE,o.HANDLEGROUP_ID as HANDLEGROUP_ID,o.HANDLEBY_ID as HANDLEBY_ID,c.CUSTOMER_ID as CUSTOMER_ID FROM objective o left join customer c on o.customer_guid=c.customer_guid left join elitetask e on o.OBJECTIVE_GUID = e.OBJECTIVE_GUID where 1=1 and o.HANDLEGROUP_ID in ('" + advisory_groupid + "')  " + account_openingid + " " + channel_id + " " + deposit_statusid + " and c.firstAssetTime is null and e.CREATEDDATE<date_add(now(), interval -"+allocation_day2+" day) and e.MAP_ID='MY48ZX'", "dataSource");

            if (objectivelist.size() > 0) {//循环遍历
                int arrInt = objectivelist.size();
                log.debug(arrInt);
                for (int i = 0; i < arrInt; i++) {
                    String OBJECTIVE_GUID = objectivelist.get(i).get("OBJECTIVE_GUID");
                    log.debug(OBJECTIVE_GUID);
                    String CUSTOMER_GUID = objectivelist.get(i).get("CUSTOMER_GUID");
                    log.debug(CUSTOMER_GUID);
                    String CREATEDDATE = objectivelist.get(i).get("CREATEDDATE");//上次分配时间
                    log.debug(CREATEDDATE);
                    String oldhandlegroup_id = objectivelist.get(i).get("HANDLEGROUP_ID");//assign_his上次处理组ID
                    log.debug(oldhandlegroup_id);
                    String oldhandleby_id = objectivelist.get(i).get("HANDLEBY_ID");//assign_his上次处理人ID
                    log.debug(oldhandleby_id);
                    //String customer_id = objectivelist.get(i).get("CUSTOMER_ID");//华盛号
                    //log.debug(customer_id);

                    String[] custTaskDealSQL = new String[4];
                    //回收objective表数据
                    custTaskDealSQL[0] = "update objective set HANDLEGROUP_ID='' ,HANDLEBY_ID='',recycledate=now(),retaindeadline='" + retain_time + "',CUSTLISTNAME='" + advisory_batchid + "',objectivesubstatus='' where OBJECTIVE_GUID='" + OBJECTIVE_GUID + "'";
                    //回收elitetask表数据
                    custTaskDealSQL[1] = "update elitetask set HANDLEGROUP_ID='' ,HANDLEBY_ID='',objectivesubstatus='',MODIFIEDDATE=null where OBJECTIVE_GUID='" + OBJECTIVE_GUID + "'";
                    //新增assign_his记录表
                    custTaskDealSQL[2] = "insert into assign_his(assign_guid,customer_guid,objective_guid,oldhandlegroup_id,oldhandleby_id,newhandlegroup_id,newhandleby_id,success_guid,lastassigndate,recovery_guid,advisory_batchid,ASSIGNGROUP_ID,ASSIGNBY_ID,ASSIGNDATE,RETURNGROUP_ID,RETURNBY_ID,RETURNDATE) VALUES (UUID(),'" + CUSTOMER_GUID + "','" + OBJECTIVE_GUID + "','" + oldhandlegroup_id + "','" + oldhandleby_id + "',null,null,'接口回收数据','" + CREATEDDATE + "','" + recovery_guid + "','" + advisory_batchid + "','SYSTEM','SELITE',NOW(),'SYSTEM','SELITE',NOW())"

                    //插入通知表
                    if (expiration_prompt == "0") {
                        List hst_leadsnoticelist = eliteBean.chaxun_sql("select count(*) as count from hst_leadsnotice where noticeType='31' and  DATE_FORMAT(createddate,'%Y-%m-%d')=DATE_FORMAT('" + expiration_prompttime + "','%Y-%m-%d') and noticeGroup='" + oldhandlegroup_id + "' and noticeBy='" + oldhandleby_id + "'", "dataSource");

                        String hst_leadsnoticenumber = hst_leadsnoticelist.get(0).get("count");

                        if (hst_leadsnoticenumber == "0") {
                            custTaskDealSQL[3] = "insert into hst_leadsnotice (noticeId,noticeGroup,noticeBy,createGroup,createBy,noticeContent,createddate,limitCount,loadCount,noticeType) VALUES (UUID(),'" + oldhandlegroup_id + "','" + oldhandleby_id + "','SYSTEM','Tao',concat('【','" + recovery_name + "','】','您有任务被回收了，且距离分配保留效期只有三天了，请知晓！'),'" + expiration_prompttime + "',2,1,'31'  )"
                        }
                    }

                    int[] batchSQLResult = eliteBean.updateBatch(custTaskDealSQL, "dataSource");
                    log.debug("SQL返回结果：" + batchSQLResult.toString());

                    /*
                    //调用解绑接口
                    String injson="{\"hsNo\""+":"+"\""+customer_id+"\"}"

                    String doURL ="";

                    String sysurl = getProperty.get("crmurl");//配置本地接口地址

                    doURL = sysurl+"aipHSTBindCounselor";

                    log.debug("doURL:" + doURL);
                    Map<String, String> headMap = new HashMap<String, String>();
                    headMap.put("Content-Type", "application/x-www-form-urlencoded");
                    def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
                    log.debug("getResult:" + getResult);
                    */
                }

                //获取数据回收总量
                List recovery_numberlist = eliteBean.chaxun_sql("select count(*) as recovery_number from assign_his where recovery_guid= '" + recovery_guid + "' and advisory_batchid = '" + advisory_batchid + "'", "dataSource");
                def recovery_number = recovery_numberlist.get(0).get("recovery_number");
                log.debug("recovery_number" + recovery_number);

                String[] custTaskDealSQL2 = new String[1];
                custTaskDealSQL2[0] = "INSERT INTO hst_recycle_check(recycle_check_guid, recovery_guid, recovery_type, recovery_number, recovery_date ,advisory_batchid,recovery_name,retain_type,retain_day) VALUES (uuid(), '" + recovery_guid + "', '按照配置规则回收', '" + recovery_number + "', now(),'" + advisory_batchid + "','" + recovery_name + "','"+retain_type+"','"+retain_day+"')"
                int[] batchSQLResult2 = eliteBean.updateBatch(custTaskDealSQL2, "dataSource");
                log.debug("SQL返回结果2：" + batchSQLResult2.toString());

                //计算下次回收时间并update hst_recycle_rules表
                def xc_recovery_time = '';//下次回收时间
                List xc_recovery_timelist = new ArrayList<>();

                if (recovery_frequency == "1") {//回收凭此为每天
                    xc_recovery_timelist = eliteBean.chaxun_sql("select date_add(NOW(), interval 1 day) as xc_recovery_time", "dataSource");//获取下次回收时间
                    xc_recovery_time = xc_recovery_timelist.get(0).get("xc_recovery_time");
                }

                if (recovery_frequency == "2") {//回收凭此为每周
                    xc_recovery_timelist = eliteBean.chaxun_sql("select date_add(NOW(), interval 1 week) as xc_recovery_time", "dataSource");//获取下次回收时间
                    xc_recovery_time = xc_recovery_timelist.get(0).get("xc_recovery_time");
                }

                if (recovery_frequency == "3") {//回收凭此为每月
                    xc_recovery_timelist = eliteBean.chaxun_sql("select date_add(NOW(), interval 1 month) as xc_recovery_time", "dataSource");//获取下次回收时间
                    xc_recovery_time = xc_recovery_timelist.get(0).get("xc_recovery_time");
                }

                if (recovery_frequency == "4") {//回收凭此为每季
                    xc_recovery_timelist = eliteBean.chaxun_sql("select date_add(NOW(), interval 1 quarter) as xc_recovery_time", "dataSource");//获取下次回收时间
                    xc_recovery_time = xc_recovery_timelist.get(0).get("xc_recovery_time");
                }

                if (recovery_frequency == "5") {//回收凭此为每年
                    xc_recovery_timelist = eliteBean.chaxun_sql("select date_add(NOW(), interval 1 year) as xc_recovery_time", "dataSource");//获取下次回收时间
                    xc_recovery_time = xc_recovery_timelist.get(0).get("xc_recovery_time");
                }

                String[] custTaskDealSQL3 = new String[1];
                custTaskDealSQL3[0] = "update hst_recycle_rules set xc_recovery_time='" + xc_recovery_time + "' where recovery_guid='" + recovery_guid + "'"
                int[] batchSQLResult3 = eliteBean.updateBatch(custTaskDealSQL3, "dataSource");
                log.debug("SQL返回结果3：" + batchSQLResult3.toString());

                outData = "{\"result\":\"1\",\"message\":\"获取对应的任务回收，任务成功\",\"data\":[]}";

            }else{
                log.debug("无匹配的回收数据！");
                String[] custTaskDealSQL2 = new String[1];
                custTaskDealSQL2[0] = "INSERT INTO hst_recycle_check(recycle_check_guid, recovery_guid, recovery_type, recovery_number, recovery_date ,advisory_batchid,recovery_name,retain_type,retain_day) VALUES (uuid(), '" + recovery_guid + "', '按照配置规则回收', '0', now(),'" + advisory_batchid + "','" + recovery_name + "','"+retain_type+"','"+retain_day+"')"
                int[] batchSQLResult2 = eliteBean.updateBatch(custTaskDealSQL2, "dataSource");
                log.debug("SQL返回结果4：" + batchSQLResult2.toString());

                outData = "{\"result\":\"1\",\"message\":\"无匹配的数据可回收，任务结束\",\"data\":[]}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"回收任务失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        return outData;
    }

}
